<script setup lang="ts">
import { ref } from 'vue';
import '@mdi/font/css/materialdesignicons.css'

import { createAlova } from 'alova'
// 
import adapterFetch from 'alova/fetch'

import hljs from 'highlight.js'

import 'highlight.js/styles/tokyo-night-dark.css'
import { Llm_id, ProcessLocate, changeIcon, changeLLM, changeList, markdownToHtml, sleep } from '../utils/utils'
import CopyButtonPlugin from 'highlightjs-copy-ts';
import 'highlightjs-copy-ts/dist/highlightjs-copy.min.css'

import { useCounterStore } from '../stores/counter'
import { useListStore } from '../stores/list'
import { useLLMStore } from '../stores/llm'
import { useInputMsgStore } from '../stores/input_msg'
import { useIconsStore } from '../stores/icons';
import { useStatusStore } from '../stores/status';
import { useOperateMapStore } from '../stores/operate_map';

const status = useStatusStore()

const counter = useCounterStore()
const lists = useListStore()
const llm = useLLMStore()
const input_msg = useInputMsgStore()
const icons = useIconsStore()
const operate_map = useOperateMapStore()
const width = ref(0)
let op = 'chat'
let post_url = ''



function initHLJS() {
    hljs.addPlugin(new CopyButtonPlugin())
}

function getWindowWidth() {
    width.value = window.innerWidth - window.innerHeight
    console.log(width.value);
}
async function reRender() {
    if (status.isCodeMode()) {
        await sleep(100)
        console.log('hljs', hljs);
        await hljs.highlightAll()
    }

}
function send_mesg(input_msg: string, post_url: string, op: string) {
    const alovaInstance = createAlova({
        requestAdapter: adapterFetch(),
        timeout: 1000 * 60 * 5, // 超时时间设置为60 * 5秒

    })

    alovaInstance
        .Post(post_url, {
            data: input_msg,
        })
        .then(response => {
            console.log('response');
            console.log(response);
            if (response.status == 200) {
                return response.json()
            } else {
                throw new Error("error");
            }
        }).then(async data => {
            console.log("op", op);

            if (op != 'chat') {
            } else {
                
                const result = markdownToHtml(data['markdown'])
                console.log("result:", result);

                result.then((markdown) => {
                    lists.add(markdown, 'bot', status.getLlmId(), data['markdown'])
                }).catch((err) => {
                    console.log('error', err);
                })
                reRender()
            }

        })
    console.log("enter！！！")
}
function change(llm_id: Llm_id) {
    changeList(llm_id, (llm_id) => {
        lists.changeCurrentList(llm_id)
    })
    changeIcon(llm_id, (llm_id) => {
        icons.changeIcons(llm_id)
    })
    changeLLM(llm_id, (llm_id) => {
        llm.change(llm_id)
        status.changeLlmId(llm_id)

    })
}
function submit() {
    counter.clearCount()
    input_msg.input_msg = input_msg.input_msg.trimEnd()
    if (operate_map.has(input_msg.input_msg)) {
        operate_map.execute(input_msg.input_msg)
    } else {
        post_url = '/api/' + status.getLlmId()
        const result = markdownToHtml(input_msg.input_msg)
        result.then((markdown) => {
            lists.add(markdown, 'user', status.getLlmId(), input_msg.input_msg)
        }).catch((err) => {
            console.log('error', err);
        })
        // lists.add(input_msg.input_msg, 'user', status.getLlmId(), input_msg.input_msg)
        op = 'chat'
    }

    if (op === 'change' || op === 'clear_local') { }
    else {
        send_mesg(input_msg.input_msg, post_url, op)
    }
}
function key_up() {
    console.log(counter.count)
    if (counter.count >= lists.currentList?.msgs.length) {
        counter.clearCount()
        return;
    }
    if (lists.currentList?.msgs.length > counter.count) {
        counter.addOne()
        counter.addOne()
        for (let i = lists.currentList?.msgs.length - counter.count; i > 0; i--) {
            if (lists.currentList?.msgs[i].id === 'user') {
                input_msg.change_current_msg(lists.currentList?.msgs[i].orign_msg )
                break;
            }
        }
    }
}
function key_down() {
    if (lists.currentList?.msgs.length > 0) {
        counter.minusOne()
        counter.minusOne()
        if (counter.count < 0) {
            counter.clearCount()
            return;
        }
        for (let i = lists.currentList?.msgs.length - counter.count; i > 0; i--) {
            if (lists.currentList?.msgs[i].id === 'user') {
                input_msg.change_current_msg(lists.currentList?.msgs[i].content)
                break;
            }
        }
    }
}
function initMap() {
    operate_map.insert(":C", {
        msg: '', processLocate: ProcessLocate.local, fuc: () => {
            lists.clear(status.getLlmId())
            op = 'clear_local'
        }
    })
    operate_map.insert(":CC", {
        msg: '', processLocate: ProcessLocate.local, fuc: () => {
            post_url = '/api/clear/all'
        }
    })
    operate_map.insert(":SC", {
        msg: '', processLocate: ProcessLocate.server, fuc: () => {
            post_url = '/api/clear/spark'
        }
    })
    operate_map.insert(":YC", {
        msg: '', processLocate: ProcessLocate.server, fuc: () => {
            post_url = '/api/clear/yiyan'
        }
    })
    operate_map.insert(":DC", {
        msg: '', processLocate: ProcessLocate.server, fuc: () => {
            post_url = '/api/clear/doubao'
        }
    })
    operate_map.insert(":QC", {
        msg: '', processLocate: ProcessLocate.server, fuc: () => {
            post_url = '/api/clear/qwen'
        }
    })
    operate_map.insert(":GC", {
        msg: '', processLocate: ProcessLocate.server, fuc: () => {
            post_url = '/api/clear/glm'
            op = 'clear_glm'
        }
    })
    operate_map.insert(":GGC", {
        msg: '', processLocate: ProcessLocate.server, fuc: () => {
            post_url = '/api/clear/gemini'
            op = 'clear_gemini'
        }
    })
    operate_map.insert(":T", {
        msg: '', processLocate: ProcessLocate.local, fuc: () => {
            input_msg.change_current_msg('in English')
            lists.add(input_msg.input_msg, 'user', status.getLlmId())
            post_url = '/api/'+ status.getLlmId()
            op = 'chat'
        }
    })
    operate_map.insert(":TC", {
        msg: '', processLocate: ProcessLocate.local, fuc: () => {
            input_msg.change_current_msg('in chinese')
            lists.add(input_msg.input_msg, 'user', status.getLlmId())
            post_url = '/api/'+ status.getLlmId()
            op = 'chat'
        }
    })
    operate_map.insert(":R", {
        msg: '', processLocate: ProcessLocate.local, fuc: () => {
            input_msg.change_current_msg('找出回答中的问题并重新生成')
            lists.add(input_msg.input_msg, 'user', status.getLlmId())
            post_url = '/api/'+ status.getLlmId()
            op = 'chat'
        }
    })
    operate_map.insert(":S", {
        msg: '', processLocate: ProcessLocate.server, fuc: () => {
            op = 'change'
            change(Llm_id.spark)
        }
    })
    operate_map.insert(":Y", {
        msg: '', processLocate: ProcessLocate.server, fuc: () => {
            op = 'change'
            change(Llm_id.yiyan)
        }
    })
    operate_map.insert(":D", {
        msg: '', processLocate: ProcessLocate.server, fuc: () => {
            op = 'change'
            change(Llm_id.doubao)

        }
    })
    operate_map.insert(":Q", {
        msg: '', processLocate: ProcessLocate.server, fuc: () => {
            op = 'change'
            change(Llm_id.qwen)
        }
    })
    operate_map.insert(":G", {
        msg: '', processLocate: ProcessLocate.server, fuc: () => {
            op = 'change'
            change(Llm_id.glm)
        }
    })
    operate_map.insert(":GG", {
        msg: '', processLocate: ProcessLocate.server, fuc: () => {
            op = 'change'
            change(Llm_id.gemini)
        }
    })
}
initMap()
initHLJS()
getWindowWidth()
</script>

<template>

    <div>

        <v-textarea label="Input" row-height="5" @keyup.enter="submit" @keyup.ctrl.enter="submit" @keyup.up="key_up"
            @keyup.down="key_down" rows="1" variant="outlined" v-model="input_msg.input_msg" auto-grow>
            <template v-slot:append-inner>
                <v-icon icon="mdi-send" class="send_icon" />
            </template></v-textarea>
    </div>

</template>

<style scoped>
.send_icon {
    color: rgba(41, 221, 221, 0.841);
}

.message_list {
    overflow-y: hidden;
}
</style>
